package com.lhq.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhq.business.domain.Tag;
import com.lhq.business.mapper.TagMapper;
import com.lhq.business.service.ITagService;
import com.lhq.common.core.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 标签分类Service业务层处理
 *
 * @author lhq
 * @date 2024-05-07
 */
@Service
public class TagServiceImpl  extends BaseServiceImpl<TagMapper,Tag>  implements ITagService
{
    @Autowired
    private TagMapper tagMapper;

    /**
     * 查询标签分类
     *
     * @param id 标签分类主键
     * @return 标签分类
     */
    @Override
    public Tag selectById(String id)
    {
        return tagMapper.selectById(id);
    }

    /**
     * 查询标签分类分页列表
     * @return 标签分类
     */
    @Override
    public IPage<Tag> selectList(Page<Tag> page,Tag tag)
    {
        QueryWrapper<Tag> queryWrapper =new QueryWrapper<>();
        return tagMapper.selectPage(page,queryWrapper);
    }

    /**
     * 新增标签分类
     *
     * @param tag 标签分类
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTag(Tag tag)
    {
        return tagMapper.insert(tag);
    }

    /**
     * 修改标签分类
     *
     * @param tag 标签分类
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTag(Tag tag)
    {
        return tagMapper.updateById(tag);
    }

    /**
     * 删除标签分类信息
     *
     * @param id 标签分类主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteById(String id)
    {
        return tagMapper.deleteById(id);
    }
    /**
     *
     * 查询标签分类树
     *
     * @author lhq
     * @date 2024/5/7 11:21
     * @version 1.0
     */
    @Override
    public List<Tag> tagTree() {
        List<Tag> tags = tagMapper.selectList(null);
        tags.stream().forEach(
                t->setSubList(tags,t)
        );
        return tags.stream()
                .filter(t-> Objects.equals(t.getParentId(), "-1"))
                .collect(Collectors.toList());
    }
    /**
     *
     * 查询并设置子标签
     *
     * @author lhq
     * @date 2024/5/7 13:57
     * @version 1.0
     */
    private  void setSubList(List<Tag> tags,Tag tag){
        List<Tag> subList =tags.stream()
                .filter(
                        t->t.getParentId()
                                .equals(tag
                                        .getId()))
                .collect(Collectors.toList());
        tag.setSubTags(subList);
    }
}
